#!/bin/sh

die() {
    echo -e "\033[31me\033[0m => $1"
    exit 1
}

model=$(cat /tmp/sysinfo/model)
[ "$model" = "Phicomm N1" ] || die "this script if only for Phicomm N1, but your device is ${model}!!"

emmc=$(lsblk | grep -oE 'mmcblk[0-9]' | sort | uniq)
dev_emmc="/dev/$emmc"

if [ $(blkid ${dev_emmc}p[1-3] | grep -E 'BOOT_EMMC|ROOT_EMMC|DATA' | wc -l) != 3 ]; then
    die "you have never installed a OS to emmc, please boot with usb and run n1-install to install at first!"
fi

image="/tmp/upgrade/*.img"
[ -f $image ] || die "no upgrade image found in /tmp/upgrade!!"

echo "start upgrade from $(ls /tmp/upgrade | grep '.img$')..."

kill "$(ps | grep dockerd | grep -v grep | awk '{print $1}')"

loop=$(losetup -P -f --show $image)
[ "$loop" ] || die "create loop device failed!!"

mnt_loop="/mnt/$(echo $loop | grep -oE 'loop[0-9]+')"
uuid=$(blkid ${loop}p2 | awk '{ print $3 }' | cut -d '"' -f 2)

[ -d ${mnt_loop}p1 ] || mkdir -p ${mnt_loop}p1
[ -d ${mnt_loop}p2 ] || mkdir -p ${mnt_loop}p2
[ $(ls ${mnt_loop}p1 | wc -l) = 0 ] && mount -t vfat ${loop}p1 ${mnt_loop}p1
[ $(ls ${mnt_loop}p2 | wc -l) = 0 ] && mount -t ext4 ${loop}p2 ${mnt_loop}p2

if [ "$uuid" ]; then
    sed -i "s/LABEL=ROOTFS/UUID=$uuid/" ${mnt_loop}p1/uEnv.txt
else
    sed -i 's/ROOTFS/ROOT_EMMC/' ${mnt_loop}p1/uEnv.txt
fi

[ -f ${mnt_loop}p2/etc/config/fstab.bak ] || cp ${mnt_loop}p2/etc/config/fstab ${mnt_loop}p2/etc/config/fstab.bak

echo && read -p "do you want to save configuration? [Y/n] " yn
case $yn in
n | N) yn='n' ;;
*) yn='y' ;;
esac

[ "$yn" = "y" ] && {
    backup="/opt/backup-OpenWrt-$(date "+%Y-%m-%d").tar.gz"
    sysupgrade -b $backup
    tar -xzf $backup -C ${mnt_loop}p2
}

(
    cd ${mnt_loop}p2/etc/config
    cp fstab.bak fstab
    sed -i "s/'BOOT'/'BOOT_EMMC'/" fstab
    if [ "$uuid" ]; then
        sed -i -e '/ROOTFS/ s/label/uuid/' fstab
        sed -i "s/ROOTFS/$uuid/" fstab
    else
        sed -i 's/ROOTFS/ROOT_EMMC/' fstab
    fi
)

cat >${mnt_loop}p2/etc/init.d/resizefs <<-EOF
#!/bin/sh /etc/rc.common

START=99

boot() {
    # mount -o rw,remount /
    /usr/sbin/resize2fs /dev/mmcblk1p2
}
EOF

chmod +x ${mnt_loop}p2/etc/init.d/resizefs
(
    cd ${mnt_loop}p2/etc/rc.d
    ln -s ../init.d/resizefs S99resizefs
)

macaddr=$(uuidgen | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\)\(..\).*$/fc:\1:\2:\3:\4:\5/')
[ "$macaddr" ] && {
    sdio="${mnt_loop}p2/lib/firmware/brcm/brcmfmac43455-sdio.phicomm,n1.txt"
    [ -f $sdio ] && sed -i "s/macaddr=b8:27:eb:74:f2:6c/macaddr=$macaddr/" $sdio
}

rm -f ${mnt_loop}p2/usr/bin/n1-install
rm -f ${mnt_loop}p2/usr/bin/beikeyun-update

tune2fs -L "ROOT_EMMC" ${loop}p2 >/dev/null

echo -e "
----------------------------
       \033[41m FBI WARNNING \033[0m
  !!! do not power off !!!
----------------------------
"

echo "upgrading boot..."
grep -w '/boot' /proc/mounts | grep -q $dev_emmc || {
    umount -f /boot 2>/dev/null
    mount -t vfat ${dev_emmc}p1 /boot
}
rm -rf /boot/*
cp -r ${mnt_loop}p1/* /boot
echo ""

echo "upgrading rootfs..."
pv -rpt ${loop}p2 | dd of=${dev_emmc}p2 conv=fsync 2>/dev/null
echo ""

echo "done, will reboot your device now!"
echo 's' >/proc/sysrq-trigger
echo 'b' >/proc/sysrq-trigger
